<script lang="ts" setup name="popupAdvertisementEdit">
import { reactive, ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { linkTypeList, activityTypeList, showPositionTypeList } from "@/utils/serviceDict";
import { ActivityFormList } from "@/types/createActivity";
import UploadImg from "@/components/Upload/Img.vue";
import { Search } from "@element-plus/icons-vue";
import SelectTreeData from "@/components/SelectTreeData/index.vue";
import { getGoodsList, getFoodCategoryList } from "@/api/modules/goods";
import { createPopupActivityAPI, getPopupAvtivityDetailAPI, editPopupActivityAPI } from "@/api/modules/activity";
import { getUserDepositRulesList } from "@/api/modules/member";
import CouponDialog from "./components/CouponDialog.vue";
import { ElForm } from "element-plus";
import { getMemberGradeList } from "@/api/modules/member";

const router = useRouter();
const route = useRoute();
onMounted(async () => {
  await getActivityDetail();
  getMemberList();
});

const formData = reactive<ActivityFormList>({
  path: "/marketing/popup-advertisement?activityId=",
  id: 0,
  name: "",
  code: "",
  desc: "",
  // activityType: 1, // 活动类型
  type: 5, // 活动类型弹窗广告活动
  validityRange: [new Date().toLocaleString(), new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toLocaleString()],
  promotionType: 1, // 活动分类
  rule: {
    urlType: 0, // 链接类型
    value: "", // 选中链接类型1.链接2商品Id 3分类Id
    image: "",
    name: "",
    showPosition: [1]
  },
  gradeType: 0,
  // storeType: 0,
  gradeList: [],
  isNonMember: false,
  isMember: false,
  prioritySortId: 0
});
const ruleList = {
  name: [{ required: true, message: "请输入活动名称" }],
  validityRange: [{ required: true, message: "请选择日期" }],
  "rule.value": [
    {
      validator(rule: any, value: any, callback: Function) {
        if ((formData.rule.urlType === 1 || formData.rule.urlType === 3) && !value) {
          callback(new Error("请选择"));
        }
        callback();
      }
    }
  ],
  "rule.showPosition": [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value.length < 1) return callback(new Error("请选择"));
        callback();
      }
    }
  ]
};

const onSelectUrl = (e: any) => {
  // 选中类型
  formData.rule.value = "";
  formData.rule.image = "";
  formData.rule.name = "";
  productUrl.value = "";
  rechargeUrl.value = "";
  formData.rule.urlType === 0
    ? (formData.rule.value = "")
    : formData.rule.urlType === 2
    ? (formData.rule.value = "/pages/user/recharge/recharge")
    : formData.rule.urlType === 3
    ? (formData.rule.value = rechargeUrl.value)
    : (formData.rule.value = productUrl.value);
};

// 选择菜品
const productUrl = ref("");
const SelectTreeDataRef = ref<InstanceType<typeof SelectTreeData> | null>(null);
const couponDialogRef = ref<InstanceType<typeof CouponDialog> | null>(null);
const openDialog = async (inputParams?: any) => {
  // 判断urlType=== 1 是菜品 urlType === 2 是充值活动
  if (formData.rule.urlType === 1) {
    SelectTreeDataRef.value?.acceptParams({
      title: "选择菜品",
      idName: "foodCategoryId",
      isView: false,
      selType: "radio",
      columns: [
        { type: "radio", label: "#", width: 60 },
        { prop: "name", label: "菜品名称", align: "left" }
      ],
      api: getGoodsList,
      apiParams: { isFoodList: 1 },
      treeApi: getFoodCategoryList
    });
  } else if (formData.rule.urlType === 3) {
    const { data } = await getUserDepositRulesList({ isAvailable: true, pageNum: 1, pageSize: 999, ...inputParams });
    couponDialogRef.value!.acceptParams({
      title: "充值活动列表(只选一个)",
      search: {
        label: "充值活动名称",
        type: "input"
      },
      tableData: data.list,
      columns: [
        { type: "selection", width: 60 },
        { prop: "name", label: "充值活动名称", width: 200 },
        { prop: "depositTypeText", label: "充值活动类型", width: 150 },
        { prop: "startTime", label: "开始时间" },
        { prop: "endTime", label: "结束时间" }
      ]
    });
  }
};
const onsearch = (e: any) => {
  formData.rule.urlType = 3;
  openDialog({ name: e.searchText });
};

const onSelectProduct = (e: any) => {
  productUrl.value = "/pages/product/product_detail?productId=" + e.data.id;
  formData.rule.value = productUrl.value;
  formData.rule.name = e.data.name;
};

// 选中活动
const rechargeUrl = ref("");
const selectCouponList = (e: any) => {
  rechargeUrl.value = "/pages/user/recharge/recharge_detail?id=" + e.tableData[0].id;
  formData.rule.value = rechargeUrl.value;
  formData.rule.name = e.tableData[0].name;
};

const onReset = () => {
  formData.rule.urlType = 3;
  openDialog();
};

// 提交数据
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const onSubmitForm = async () => {
  await formRef.value?.validate();
  console.log(formData.gradeList);

  if (route.query.activityId) {
    await editPopupActivityAPI(formData);
  } else {
    await createPopupActivityAPI(formData);
  }
  router.push("/marketing/coupon-scan?upList=" + true);
};

// 获取编辑数据
const getActivityDetail = async () => {
  if (!route.query.activityId) return;
  const res: any = await getPopupAvtivityDetailAPI({ id: route.query.activityId });
  Object.keys(formData).forEach(key => {
    if (res.data.hasOwnProperty(key)) {
      formData[key] = res.data[key];
    }
  });
};

// 获取会员数组
const memberList = ref<any[]>([]);
const getMemberList = async () => {
  const res = await getMemberGradeList({ pageNum: 1, pageSize: 9999 });
  memberList.value = JSON.parse(JSON.stringify(res.data.list));
  if (route.query.activityId) {
    memberList.value.forEach(v => {
      formData.gradeList!.forEach((i: any) => {
        if (v.id === i) {
          v.checked = true;
        }
      });
    });
  }
};
// 切换非会员和会员时将会员数组清空
const onChangeMember = (type: string) => {
  if (type === "isMember") {
    if (!formData.isMember) {
      formData.gradeType = 0;
      formData.gradeList = [];
    }
  } else {
    formData.gradeList = [];
  }
};
</script>

<template>
  <div class="popupAdvertisementEdit-box">
    <el-card style="max-width: 100%; min-height: 100%">
      <template #header>
        <div class="card-header">
          <div style="display: flex; align-items: center" @click="router.back()">
            <el-icon size="20"><ArrowLeft /></el-icon>
            <span style="margin-left: 5px">弹窗广告</span>
          </div>
          <div v-if="route.query.type === 'view' ? false : true">
            <el-button type="primary" @click="onSubmitForm">保存</el-button>
          </div>
        </div>
      </template>

      <!-- 内容 -->
      <div class="content">
        <div class="left">
          <div class="top-nav">
            <img src="@/assets/images/topNavBlack.png" />
          </div>
          <div class="preview">
            <div class="mark">
              <!-- 广告 -->
              <div class="advertising-box">
                <div v-if="!formData.rule.image" class="img-none">
                  <el-icon size="50"><Picture /></el-icon>
                  <div>请上传图片</div>
                </div>
                <img v-else style="width: 100%; height: 100%" :src="formData.rule.image" alt="" />
                <!-- <el-button>确认领取</el-button> -->
              </div>
              <div style="display: flex; justify-content: center; margin-top: 20px">
                <el-icon size="25" color="#ccc"><CircleClose /></el-icon>
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="title">基础信息</div>
          <el-form ref="formRef" :model="formData" :rules="ruleList" class="info-form" label-width="120" label-position="left">
            <el-form-item prop="name" label="活动名称:">
              <el-input placeholder="请输入" v-model="formData.name"></el-input>
            </el-form-item>
            <el-form-item prop="code" label="活动编码:">
              <el-input placeholder="请输入活动编码" v-model="formData.code"></el-input>
            </el-form-item>

            <!-- <el-form-item prop="code" label="活动类型:">
              <el-select v-model="formData.activityType">
                <el-option v-for="item in activityTypeList" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item> -->

            <el-form-item prop="validityRange" label="活动日期:">
              <el-date-picker
                v-model="formData.validityRange"
                type="datetimerange"
                format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>

            <el-form-item prop="desc" label="活动说明:">
              <el-input type="textarea" v-model="formData.desc"></el-input>
            </el-form-item>
            <el-form-item label="链接类型:" v-if="formData.activityType !== 2">
              <el-select @change="onSelectUrl" v-model="formData.rule.urlType">
                <el-option v-for="item in linkTypeList" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="菜品名称:" v-if="formData.activityType !== 2 && formData.rule.urlType === 1">
              <el-input v-model="formData.rule.name" disabled></el-input>
            </el-form-item>
            <!-- 选择活动详细 -->
            <el-form-item label="充值活动名称:" v-if="formData.activityType !== 2 && formData.rule.urlType === 3">
              <el-input v-model="formData.rule.name" disabled></el-input>
            </el-form-item>

            <el-form-item prop="rule.value" label="活动链接" v-if="formData.activityType !== 2 && formData.rule.urlType">
              <el-input v-model="formData.rule.value" disabled>
                <template #append>
                  <el-button
                    @click="openDialog"
                    v-if="formData.rule.urlType === 1 || formData.rule.urlType === 3"
                    :icon="Search"
                  />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="prioritySortId" label="活动优先级">
              <el-input-number style="width: 100%" :controls="false" :min="0" v-model="formData.prioritySortId"></el-input-number>
              <div style="font-size: 14px; color: #999999">活动在相同的时间，平台只会显示其中优先级最高的活动</div>
            </el-form-item>

            <el-form-item label="弹窗展示位置：" prop="rule.showPosition">
              <el-checkbox-group v-model="formData.rule.showPosition">
                <el-checkbox v-for="item in showPositionTypeList" :value="item.value" :label="item.label" :key="item.value" />
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="会员选择：">
              <el-checkbox v-model="formData.isNonMember">非会员</el-checkbox>
              <el-checkbox @change="onChangeMember('isMember')" v-model="formData.isMember">会员</el-checkbox>
            </el-form-item>

            <el-form-item label="适用会员：" v-if="formData.isMember">
              <el-radio-group @change="onChangeMember('gradeType')" v-model="formData.gradeType">
                <el-radio :value="0">全部会员</el-radio>
                <el-radio :value="1">指定会员</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item
              :rules="formData.gradeType ? [{ required: true, message: '请选择指定会员' }] : [{ required: false }]"
              prop="gradeList"
              label="指定会员选择:"
              v-if="formData.gradeType && formData.isMember"
            >
              <el-checkbox-group v-model="formData.gradeList" @change="changeGradeList">
                <el-checkbox
                  :checked="item.checked"
                  :label="item.title"
                  :value="item.id"
                  v-for="item in memberList"
                  :key="item.id"
                />
              </el-checkbox-group>
            </el-form-item>

            <el-form-item prop="rule.image" label="上传图片:" :rules="[{ required: true, message: '请上传图片' }]">
              <uploadImg v-model:image-url="formData.rule.image">
                <template #empty>
                  <el-icon><Picture /></el-icon>
                  <span>请上传图片</span>
                </template>
              </uploadImg>
            </el-form-item>
            <el-form-item>
              <div style="color: #999999">建议图片尺寸比例：1 : 1.5（例：宽: 498px; 高: 748px）</div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>
    <SelectTreeData ref="SelectTreeDataRef" @radio="onSelectProduct"></SelectTreeData>
    <CouponDialog @on-reset="onReset" @on-confirm="selectCouponList" @on-search="onsearch" ref="couponDialogRef"></CouponDialog>
  </div>
</template>

<style lang="scss" scoped>
.popupAdvertisementEdit-box {
  height: 100%;
  background-color: #ffffff;
  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 18px;
    cursor: pointer;
  }
  .content {
    box-sizing: border-box;
    display: flex;
    overflow: auto;
    .left {
      width: 375px;
      height: 100%;
      overflow: hidden;
      border: 1px solid #e8e8e8;
      .top-nav {
        height: 80px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .preview {
        position: relative;
        box-sizing: border-box;
        height: calc(100vh - 30vh - 80px);
        background: url("@/assets/images/mobile-bgc.jpg");
        background-size: 100% 100%;
      }
      .mark {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        content: "";
        background-color: rgb(0 0 0 / 50%);
        .advertising-box {
          width: 50%;
          height: 45%;
          margin: 30% auto 0;
          background-color: #ffffff;
          .img-none {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
          }
        }
      }
    }
    .right {
      width: 40%;
      margin-left: 20px;
      .title {
        padding-left: 15px;
        margin-bottom: 20px;
        font-size: 18px;
        border-left: 5px solid #ffc700;
      }
      .info-form {
        padding: 20px;
        padding-left: 50px;
      }
    }
  }
}
</style>
